<template>
	<div id="app">
		<router-view v-if="isRouterAlive"></router-view>

	</div>
</template>

<script>
	//	import SockJS from 'sockjs-client';
	//	import Stomp from 'stompjs'; 
	var stompClient = null;
	var timer = null
	export default {
		name: 'app',
		provide() {
			return {
				reload: this.reload,
				socket: null,
				stompClient: null,
			}
		},
		data() {
			return {
				isRouterAlive: true,
				socket: null,
				user_id: ''
			}
		},
		methods: {
			reload() {
				this.isRouterAlive = false;
				this.$nextTick(function() {
					this.isRouterAlive = true;
				})
			},
			initWebSocket() {
				this.connection();
				let self = this;
				// 断开重连机制,尝试发送消息,捕获异常发生时重连
				//				this.timer = setInterval(() => {
				//					
				//				}, 100000000);
				try {
					self.stompClient.send("test");
				} catch(err) {
					console.log("断线了: " + err);
					self.connection();
				}
			},
			connection() {
				// 建立连接对象
				this.socket = new SockJS('http://192.168.6.87:8081/endpoint'); //连接服务端提供的通信接口，连接以后才可以订阅广播消息和个人消息
	
				// 获取STOMP子协议的客户端对象
				stompClient = Stomp.over(this.socket);
				let userId = 1;
						//  向服务器发起websocket连接
				stompClient.connect({}, function() {
					//		订阅广播消息
					stompClient.subscribe('/topic/getResponse', function(response) { //
						console.log(response.body); 
					});
					// 个人消息
					stompClient.subscribe('/user/1/message', function(response) {
						console.log(response);
					});
				}, (err) => {
					console.log(err)
				});
			},
			disconnect() {
				if(this.stompClient != null) {
					this.stompClient.disconnect();
					console.log("Disconnected");
				}
			}
		},
		mounted() {
			this.user_id = localStorage.getItem('user_id') // 连接每个人物的id
//			this.connection();
		},
		beforeDestroy: function() {
			// 页面离开时断开连接,清除定时器
			this.disconnect();
			clearInterval(this.timer);
		},
	}
</script>